package xyz.syyrjx.blog.controller.tool.ai;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import xyz.syyrjx.blog._enum.State;
import xyz.syyrjx.blog.dao.ai.AiIdentityDao;
import xyz.syyrjx.blog.entity.ai.AiDialogue;
import xyz.syyrjx.blog.entity.ai.AiIdentity;
import xyz.syyrjx.blog.entity.Result;
import xyz.syyrjx.blog.exception.AiException;
import xyz.syyrjx.blog.service.AiService;
import xyz.syyrjx.blog.service.ToolService;
import xyz.syyrjx.blog.util.CachePool;
import xyz.syyrjx.blog.util.ConstValuePool;
import xyz.syyrjx.blog.util.ai.AiIdentityFlagUtil;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @author 大地崩坏苍蝇兽
 * @date 2024/2/4 12:43
 * @description 尝试对接api模型
 * @since v0.0.1
 */
@Controller
public class AiController {
    private static final Logger logger = LoggerFactory.getLogger(AiController.class);

    @Value("${ai.dialogue.socket.url}")
    private String aiDialogueSocketUrl;

    @Resource
    private AiService aiService;
    @Resource
    private ToolService toolService;

    @Resource
    private AiIdentityDao aiIdentityDao;


    @RequestMapping("/tools/ai")
    public ModelAndView aiPage(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession();
            if (session.getAttribute("ifAi") == null) {
                toolService.updateView(3);
                session.setAttribute("ifAi",1);
            }
            // 验证身份，添加身份标识
            String identity = AiIdentityFlagUtil.getAiIdentity(request);
            if (identity == null) {
                identity = UUID.randomUUID().toString();
                AiIdentity aiIdentity = new AiIdentity(null, identity, new Date(), State.NORMAL_STATE.getCode());
                aiIdentityDao.insertIdentity(aiIdentity);
                Cookie cookie = new Cookie(ConstValuePool.AI_IDENTITY_FLAG, identity);
                cookie.setMaxAge(ConstValuePool.COOKIE_MAX_AGE);
                response.addCookie(cookie);
                // 系统缓存中也添加
                CachePool.initAiIdentiy(identity);
            }
            // 设置ai用量表，ai对话表
            if (!CachePool.AI_USAGE_MAP.containsKey(identity)) {
                CachePool.initAiIdentiy(identity);
            }
            mv.setViewName("/tools/ai");
            return mv;
        }catch (Exception e) {
            Throwable t = e;
            while (t != null) {
                logger.error("ai页面发生错{}",t.toString());
                t = t.getCause();
            }
            throw new AiException("ai页面发生了错误，可能是由于您的身份标识过期，请尝试刷新页面获取新的身份标识,如果刷新后依然显示报错，请联系管理员解决",e);
        }
    }

    @PostMapping("/tools/ai/submitQuestion")
    @ResponseBody
    public Result submitQuestion(String model, String prompt,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
        try {
            if (ConstValuePool.WANX_MODEL.equals(model)){
                return Result.create(
                        Result.IMAGE_SUCCESS_CODE,
                        aiService.getAnswer(model, prompt, request, response),
                        null
                );
            }
            return Result.success(
                    aiService.getAnswer(model, prompt, request, response)
            );
        }catch (Exception e) {
            Throwable t = e;
            while (t != null) {
                logger.error("ai调用报错：{}",t.toString());
                t = t.getCause();
            }
            return Result.fail(e.getMessage());
        }
    }

    @PostMapping("/tools/ai/historyDialogues")
    @ResponseBody
    public Result historyDialogus(String model, HttpServletRequest request) {
        String identity = AiIdentityFlagUtil.getAiIdentity(request);
        if (identity == null) {
            return Result.fail("无法查询到您的ai对话记录表，请尝试刷新重试");
        }
        List<AiDialogue> res = null;
        switch (model){
            case ConstValuePool.QWEN_MODEL:
                res = CachePool.AI_DIALOGUE_LIST_MAP.get(identity)
                        .get(ConstValuePool.QWEN_DIALOGUES);
                break;
            case ConstValuePool.CHATGPT_MODEL:
                res = CachePool.AI_DIALOGUE_LIST_MAP.get(identity)
                        .get(ConstValuePool.CHAT_DIALOGUES);
                break;
            case ConstValuePool.GPT4_MODEL:
                res = CachePool.AI_DIALOGUE_LIST_MAP.get(identity)
                        .get(ConstValuePool.GPT4_DIALOGUES);
                break;
            case ConstValuePool.WANX_MODEL:
                res = CachePool.AI_DIALOGUE_LIST_MAP.get(identity)
                        .get(ConstValuePool.WANX_DIALOGUES);
                break;
        }
        if (res == null) {
            res = ConstValuePool.EMPTY_AI_DIALOGUE_LIST;
        }
        return Result.success(res);
    }

    @PostMapping("/tools/ai/allAiModel")
    @ResponseBody
    public Result allAiModel() {
        return Result.success(aiService.getAllAiModels());
    }

    @GetMapping("/tools/ai/aiDialogueSocketUrl")
    @ResponseBody
    public Result getAiDialogueSocketUrl() {
        return Result.success(aiDialogueSocketUrl);
    }
}
